<?php

namespace App\Http\Controllers\SystemManagement;

use App\Http\Controllers\IndexController;
use App\Models\Constant\Fields;
use App\Models\SystemManagement\Department;
use App\Models\SystemManagement\Employee;
use App\Models\SystemManagement\DepartmentEmployee;
use App\Models\SystemManagement\Organization;
use App\Models\SystemManagement\Post;
use App\Models\SystemManagement\Skill;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

/**
 * Class EmployeeController
 * @package App\Http\Controllers\SystemManagement
 * @group 员工管理
 */
class EmployeeController extends IndexController
{
    /**
     * 新增员工
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam name string required 员工姓名
     * @bodyParam id_type string required 证件类型 1居民身份证 2出生证 3护照
     * @bodyParam id_no string required 证件号码
     * @bodyParam id_start_time date required 证件生效日期
     * @bodyParam id_end_time date required 证件失效日期
     * @bodyParam birthday date required 出生日期
     * @bodyParam phone string required 电话号码
     * @bodyParam email string required 邮箱
     * @bodyParam education string required 学历
     * @bodyParam college text required 毕业院校
     * @bodyParam major string required 专业
     * @bodyParam age string required 年龄
     * @bodyParam sex int required 性别 1男 0女
     * @bodyParam residence string 户籍所在地
     * @bodyParam address text required 住址
     * @bodyParam nation string required 民族
     * @bodyParam bank_name text required 开户行
     * @bodyParam account string required 银行账号
     * @bodyParam organization_id int required 组织id 外键 组织表
     * @bodyParam department_id int required 部门id 外键 部门表
     * @bodyParam post_id int required 岗位id 外键 岗位表
     * @bodyParam skill_id int required 职级id 外键 职级表
     * @bodyParam emergency_contact string required 紧急联系人
     * @bodyParam emergency_phone string required 紧急联系人电话
     * @bodyParam emergency_relation string required 紧急联系人关系
     * @bodyParam entry_time date required 入职时间
     * @bodyParam photo_id string 照片 外键 文件统一上传接口回传id
     *
     * @response 201 {"code":201,"msg":"created","data":"新增成功"}
     * @response 400 {"code":400,"msg":"param error","data":"新增失败"}
     */
    public function store(Request $request){
        $data = $request->input();
        return Employee::addData($data);
    }

    /**
     * 修改员工
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam id int required 员工id
     * @bodyParam name string required 员工姓名
     * @bodyParam id_type string required 证件类型 1居民身份证 2出生证 3护照
     * @bodyParam id_no string required 证件号码
     * @bodyParam id_start_time date required 证件生效日期
     * @bodyParam id_end_time date required 证件失效日期
     * @bodyParam birthday date required 出生日期
     * @bodyParam phone string required 电话号码
     * @bodyParam email string required 邮箱
     * @bodyParam education string required 学历
     * @bodyParam college text required 毕业院校
     * @bodyParam major strng required 专业
     * @bodyParam age string required 年龄
     * @bodyParam sex int required 性别 1男 0女
     * @bodyParam residence string 户籍所在地
     * @bodyParam address text required 住址
     * @bodyParam nation string required 民族
     * @bodyParam photo string required 照片
     * @bodyParam bank_name text required 开户行
     * @bodyParam account string required 银行账号
     * @bodyParam organization_id int required 组织id 外键 组织表
     * @bodyParam department_id int required 部门id 外键 部门表
     * @bodyParam post_id int required 岗位id 外键 岗位表
     * @bodyParam skill_id int required 职级id 外键 职级表
     * @bodyParam emergency_contact string required 紧急联系人
     * @bodyParam emergency_phone string required 紧急联系人电话
     * @bodyParam emergency_relation string required 紧急联系人关系
     * @bodyParam entry_time date required 入职时间
     * @bodyParam photo_id string 照片 外键 文件统一上传接口回传id
     *
     * @response 205 {"code":205,"msg":"updated","data":"修改成功"}
     * @response 400 {"code":205,"msg":"param error","data":"修改失败"}
     */
    public function upEmp(\App\Http\Requests\System\Employee $request,$id){
        $data = $request->input();
        return Employee::updateData($data,$id);
    }

    /**
     * 员工列表-分页
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam name string 员工姓名
     * @bodyParam id_no string 证件号码
     * @bodyParam mark string 工号
     * @bodyParam department_id int 部门id
     * @bodyParam entry_start_time date 开始时间
     * @bodyParam entry_end_time date 结束时间
     *
     * @queryParam mark 工号
     * @queryParam name 员工姓名
     * @queryParam id_type 证件类型 1居民身份证 2出生证 3护照
     * @queryParam id_no 证件号码
     * @queryParam id_start_time 证件生效日期
     * @queryParam id_end_time 证件失效日期
     * @queryParam birthday 出生日期
     * @queryParam phone 电话号码
     * @queryParam email 邮箱
     * @queryParam education 学历
     * @queryParam college 毕业院校
     * @queryParam major 专业
     * @queryParam age 年龄
     * @queryParam sex 性别 1男 0女
     * @queryParam residence 户籍所在地
     * @queryParam address 住址
     * @queryParam nation 民族
     * @queryParam photo 照片
     * @queryParam bank_name 开户行
     * @queryParam account 银行账号
     * @queryParam organization_id 组织id
     * @queryParam organization->name 组织名称
     * @queryParam department_id 部门id
     * @queryParam department->name 部门名称
     * @queryParam post_id 岗位id
     * @queryParam post->name 岗位名称
     * @queryParam skill_id 职级id
     * @queryParam skill->name 职级名称
     * @queryParam emergency_contact 紧急联系人
     * @queryParam emergency_phone 紧急联系人电话
     * @queryParam emergency_relation 紧急联系人关系
     * @queryParam entry_time date required 入职时间
     * @queryParam files->file->local_url string 附件url地址
     *
     * @response 200 {"code":200,"msg":"success","data":"查询成功"}
     */
    public function index(Request $request){
        $data = Employee::getListByCond($request);
        return response()->json(encodeMsg($data,200));
    }

    /**
     * 员工列表-条件搜索
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam organization_id int 组织id 外键 组织表
     * @bodyParam department_id int 部门id 外键 部门表
     * @bodyParam post_id int 岗位id 外键 岗位表
     * @bodyParam name string 员工姓名
     *
     * @queryParam mark 工号
     * @queryParam name 员工姓名
     * @queryParam id_type 证件类型 1居民身份证 2出生证 3护照
     * @queryParam id_no 证件号码
     * @queryParam id_start_time 证件生效日期
     * @queryParam id_end_time 证件失效日期
     * @queryParam birthday 出生日期
     * @queryParam phone 电话号码
     * @queryParam email 邮箱
     * @queryParam education 学历
     * @queryParam college 毕业院校
     * @queryParam major 专业
     * @queryParam age 年龄
     * @queryParam sex 性别 1男 0女
     * @queryParam residence 户籍所在地
     * @queryParam address 住址
     * @queryParam nation 民族
     * @queryParam photo 照片
     * @queryParam bank_name 开户行
     * @queryParam account 银行账号
     * @queryParam organization_id 组织id
     * @queryParam organization->name 组织名称
     * @queryParam department_id 部门id
     * @queryParam department->name 部门名称
     * @queryParam post_id 岗位id
     * @queryParam post->name 岗位名称
     * @queryParam skill_id 职级id
     * @queryParam skill->name 职级名称
     * @queryParam emergency_contact 紧急联系人
     * @queryParam emergency_phone 紧急联系人电话
     * @queryParam emergency_relation 紧急联系人关系
     * @queryParam entry_time date required 入职时间
     * @queryParam files->file->local_url string 附件url地址
     *
     * @response 200 {"code":200,"msg":"success","data":"查询成功"}
     */
    public function getDataByCond(Request $request)
    {
        $data = Employee::orderBy('id','desc')
                ->where(function($query) use ($request){
                    $organization_id = $request->input('organization_id','');
                    $department_id = $request->input('department_id','');
                    $post_id = $request->input('post_id','');
                    $name = $request->input('name');
                    if(!empty($organization_id)) {
                        $query->where('organization_id',$organization_id);
                    }
                    if(!empty($department_id)) {
                        $query->where('department_id',$department_id);
                    }
                    if(!empty($post_id)) {
                        $query->where('post_id',$post_id);
                    }
                    if(!empty($name)) {
                        $query->where('name','like','%'.$name.'%');
                    }
                })
                ->with(['organization','department','post','skill','files'])
                ->get();
        if(count($data) == 0){
            return response()->json(encodeMsg("没有数据",404));
        }
        return response()->json(encodeMsg($data,200));
    }

    /**
     * 员工列表-不带分页
     * @return \Illuminate\Http\JsonResponse
     * @queryParam id int 员工id
     * @queryParam name string 员工姓名
     *
     * @response 200 {"code":200,"msg":"success","data":"查询成功"}
     * @response 404 {"code":404,'msg':'failed','data':"还未新增员工"}
     */
    public function getAll(){
        $list = Employee::get(['id','name']);
        if($list->isEmpty()){
            return response()->json(encodeMsg("还未新增员工",404));
        }
        return response()->json(encodeMsg($list,200));
    }

    /**
     * 查看员工
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam id 员工id
     *
     * @queryParam mark 工号
     * @queryParam name 员工姓名
     * @queryParam id_type 证件类型 1居民身份证 2出生证 3护照
     * @queryParam id_no 证件号码
     * @queryParam id_start_time 证件生效日期
     * @queryParam id_end_time 证件失效日期
     * @queryParam birthday 出生日期
     * @queryParam phone 电话号码
     * @queryParam email 邮箱
     * @queryParam education 学历
     * @queryParam college 毕业院校
     * @queryParam major 专业
     * @queryParam age 年龄
     * @queryParam sex 性别 1男 0女
     * @queryParam residence 户籍所在地
     * @queryParam address 住址
     * @queryParam nation 民族
     * @queryParam photo 照片
     * @queryParam bank_name 开户行
     * @queryParam account 银行账号
     * @queryParam organization_id 组织id
     * @queryParam department_id 部门id
     * @queryParam post_id 岗位id
     * @queryParam skill_id 职级id
     * @queryParam emergency_contact 紧急联系人
     * @queryParam emergency_phone 紧急联系人电话
     * @queryParam emergency_relation 紧急联系人关系
     * @queryParam entry_time date required 入职时间
     * @queryParam files->file->local_url string 附件url地址
     *
     * @response 200 {"code":200,"msg":"success","data":"查询成功"}
     * @response 404 {"code":404,'msg':'failed','data':"没有该员工记录"}
     */
    public function showEmp($id){
        return $this->show($id,new Employee());
    }

    /**
     * 批量删除员工
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam ids array required 员工id（数组格式）
     *
     * @response 204 {"code":204,"msg":"deleted","data":"删除成功"}
     */
    public function del(Request $request){
        return $this->delete($request,new Employee());
    }

    /**
     * 查看员工数据权限
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam id 员工id
     *
     * @queryParam employee_id 员工id
     * @queryParam department_id 部门id
     */
    public function getPrivilegeById($id)
    {
        $list = DepartmentEmployee::where('employee_id',$id)->get();
        if($list->isEmpty()){
            return response()->json(encodeMsg("该员工权限未设置",404));
        }
        return response()->json(encodeMsg($list,200));
    }

    /**
     * 员工信息导入 excel
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam name string required 员工姓名
     * @bodyParam id_type string required 证件类型 1居民身份证 2出生证 3护照
     * @bodyParam id_no string required 证件号码
     * @bodyParam id_start_time date required 证件生效日期
     * @bodyParam id_end_time date required 证件失效日期
     * @bodyParam birthday date required 出生日期
     * @bodyParam phone string required 电话号码
     * @bodyParam email string required 邮箱
     * @bodyParam education string required 学历
     * @bodyParam college text required 毕业院校
     * @bodyParam major string required 专业
     * @bodyParam age string required 年龄
     * @bodyParam sex int required 性别 1男 0女
     * @bodyParam residence string 户籍所在地
     * @bodyParam address text required 住址
     * @bodyParam nation string required 民族
     * @bodyParam photo string required 照片
     * @bodyParam bank_name text required 开户行
     * @bodyParam account string required 银行账号
     * @bodyParam organization_id int required 组织id 外键 组织表
     * @bodyParam department_id int required 部门id 外键 部门表
     * @bodyParam post_id int required 岗位id 外键 岗位表
     * @bodyParam skill_id int required 职级id 外键 职级表
     * @bodyParam emergency_contact string required 紧急联系人
     * @bodyParam emergency_phone string required 紧急联系人电话
     * @bodyParam emergency_relation string required 紧急联系人关系
     * @bodyParam entry_time date required 入职时间
     *
     * @response 201 {"code":201,"msg":"created","data":"文件已上传"}
     * @response 400 {"code":400,"msg":"param error","data":"导入失败"}
     */
    public function import(Request $request)
    {
        $data = excelImport($request);
        $employees = [];
        if(!empty($data)){
            foreach ($data as $k => $v) {
                unset($v[0]);
                foreach ($v as $key => $row) {
                    DB::beginTransaction();
                    try {
                        $employees[$k][$key]['name'] = $row[0];
                        switch ($row[1]) {
                            case '居民身份证':
                                $employees[$k][$key]['id_type'] = 1;
                                break;
                            case '出生证':
                                $employees[$k][$key]['id_type'] = 2;
                                break;
                            case '护照':
                                $employees[$k][$key]['id_type'] = 3;
                                break;
                            default:
                                $employees[$k][$key]['id_type'] = 1;
                                break;
                        }
                        $employees[$k][$key]['id_no'] = $row[2];
                        $employees[$k][$key]['id_start_time'] = $row[3];
                        $employees[$k][$key]['id_end_time'] = $row[4];
                        $employees[$k][$key]['birthday'] = $row[5];
                        $employees[$k][$key]['phone'] = $row[6];
                        $employees[$k][$key]['email'] = $row[7];
                        $employees[$k][$key]['education'] = $row[8];
                        $employees[$k][$key]['college'] = $row[9];
                        $employees[$k][$key]['age'] = $row[10];
                        switch ($row[11]) {
                            case '男':
                                $employees[$k][$key]['sex'] = 0;
                                break;
                            case '女':
                                $employees[$k][$key]['sex'] = 1;
                                break;
                            default:
                                $employees[$k][$key]['sex'] = 0;
                                break;
                        }
                        $employees[$k][$key]['address'] = $row[12];
                        $employees[$k][$key]['nation'] = $row[13];
                        $employees[$k][$key]['bank_name'] = $row[14];
                        $employees[$k][$key]['account'] = $row[15];
                        //所属公司
                        $organization_id = Organization::where('name',$row[16])->first('id');
                        if (!empty($organization_id)) {
                            $employees[$k][$key]['organization_id'] = $organization_id->id;
                        } else if(!empty($row[16])) {
                            $info = Organization::create($row[16]);
                            $employees[$k][$key]['organization_id'] = $info->id;
                        }
                        //所属部门
                        $department_id = Department::where('name',$row[17])->first('id');
                        if (!empty($department_id)) {
                            $employees[$k][$key]['department_id'] = $department_id->id;
                        } else if(!empty($row[17])) {
                            $department['name'] = $row[17];
                            $info = Department::addData($department);
                            $employees[$k][$key]['department_id'] = $info->id;
                        }
                        //岗位
                        $post_id = Post::where('name',$row[18])->first('id');
                        if (!empty($post_id)) {
                            $employees[$k][$key]['post_id'] = $post_id->id;
                        } else if(!empty($row[18])) {
                            $post['name'] = $row[18];
                            $info = Post::addData($post);
                            $employees[$k][$key]['post_id'] = $info->id;
                        }
                        //职级
                        $skill_id = Skill::where('name',$row[19])->first('id');
                        if (!empty($skill_id)) {
                            $employees[$k][$key]['skill_id'] = $skill_id->id;
                        } else if(!empty($row[19])) {
                            $info = Skill::create($row[19]);
                            $employees[$k][$key]['skill_id'] = $info->id;
                        }
                        $employees[$k][$key]['emergency_contact'] = $row[20];
                        $employees[$k][$key]['emergency_phone'] = $row[21];
                        $employees[$k][$key]['emergency_relation'] = $row[22];
                        $res = Employee::where($employees[$k][$key])->first();
                        if (empty($res)) {
                            Employee::addData($employees[$k][$key]);
                        }
                        DB::commit();
                    } catch (QueryException $e) {
                        DB::rollBack();
                        // dd($e);
                        return response()->json(encodeMsg(['message' => '导入失败!'],400));
                    }
                }
                unset($employees[$k][$key]);
            }
            unset($employees[$k]);
        }
        if(Storage::disk('public')->exists('uploads/'.$request->file('file')->getClientOriginalName())) {
            return response()->json(encodeMsg(['message' => '文件已上传!'],200));
        }
    }
}
